import vue from '@vitejs/plugin-vue'

import { defineConfig, loadEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import { createHtmlPlugin } from 'vite-plugin-html'

import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'

// import pxtovw from 'postcss-px-to-viewport'
// const loder_pxtovw = pxtovw({
//   // 这里是设计稿宽度 自己修改
//   viewportWidth: 1920,
//   viewportUnit: 'vw',
// })

// https://vitejs.dev/config/
export default ({ mode }) =>
	defineConfig({
		build: {
			// 生产环境时移除console.log()
			minify: 'terser',
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true
				}
			},
			rollupOptions: {
				output: {
					//静态资源分类打包
					chunkFileNames: 'static/js/[name]-[hash].js',
					entryFileNames: 'static/js/[name]-[hash].js',
					assetFileNames: 'static/[ext]/name-[hash].[ext]'
				}
			}
		},
		css: {
			postcss: {
				// plugins: [loder_pxtovw],
			}
		},
		plugins: [
			vue(),
			// keepalive 组件name 配置
			vueSetupExtend(),
			// 打包资源分析 stats.html
			visualizer({
				open: false,
				emitFile: false,
				//分析图生成的文件名
				file: 'stats.html'
			}),
			// mock 插件
			viteMockServe({
				mockPath: './mock/',
				logger: true,
				prodEnabled: true
			}),
			// vite 打包压缩
			viteCompression({
				verbose: true,
				disable: false,
				deleteOriginFile: false,
				// 对于大于1M的文件进行压缩
				// threshold: 1024000,
				algorithm: 'gzip',
				ext: '.gz'
			}),
			// 网页 title 配置插件
			createHtmlPlugin({
				inject: {
					data: {
						//获取标题变量
						title: loadEnv(mode, process.cwd())['VITE_APP_TITLE']
					}
				}
			}),
			// element ui 按需导入
			AutoImport({
				imports: ['vue', 'vue-router', 'vuex'],
				resolvers: [
					ElementPlusResolver(),
					IconsResolver({
						prefix: 'Icon'
					})
				]
			}),
			Components({
				resolvers: [
					ElementPlusResolver(),
					IconsResolver({
						// ep 是 Element Plus 的缩写
						enabledCollections: ['ep']
					})
				]
			}),
			Icons({
				autoInstall: true
			})
		],
		server: {
			port: 1212,
			open: false,
			host: '0.0.0.0',
			// 主要是下面两行的配置文件，不要忘记引入 fs 和 path 两个对象
			// https: {
			//   cert: fs.readFileSync(path.join(__dirname, './cert.crt')),
			//   key: fs.readFileSync(path.join(__dirname, './cert.key')),
			// },
			proxy: {
				'/api': {
					secure: false,
					changeOrigin: true,
					target: 'https://192.168.0.102',
					rewrite: path => path.replace(/^\/api/, '')
				}
			}
		}
	})
